<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名字" width="100" sortable>
      </el-table-column>
      <el-table-column prop="tel" label="联系电话" width="100" sortable>
      </el-table-column>
      <el-table-column prop="address" label="地址" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="80" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state==1" style="color: #13ce66">待审核</span>
          <span v-if="scope.row.state==2" style="color: red">待激活</span>
          <span v-if="scope.row.state==3" style="color: red">激活成功</span>
          <span v-if="scope.row.state==4" style="color: red">驳回</span>
        </template>
      </el-table-column>
      <el-table-column prop="logo" label="logo" width="180" sortable>
      </el-table-column>

      <el-table-column prop="admin.username" label="管理员" width="100" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="query.pageSize"
                     :total="pageInfo.total"
                     :current-page="query.currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" >
          <el-input v-model="addForm.password" auto-complete="off" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" >
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" >
          <el-input v-model="addForm.headimage" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
        </el-form-item>

<!--        级联框-->
        <el-form-item label="所属部门">
          <el-cascader v-model="addForm.department"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}">

          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {getUserListPage, removeUser, batchRemoveUser, editUser, addUser} from '../../api/api';

export default {
  data() {
    return {
      filters: {
        name: ''
      },
      shop: [],


      pageInfo: {
        total: 0,
        rows: []
      },
      query: {
        currentPage: 1,
        pageSize: 10,
        keyword: ""
      },
      listLoading: false,
      sels: [],//列表选中列


      deptTree:[],//表现新增或修改时，查询到的部门
      saveFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          // {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
      //新增界面数据
      addForm: {
        username: '',
        password:'',
        age: 0,
        email:"",
        headimage:"",
        department:{
          id:null,
          name:"",
        }
      },
      path:""

    }
  },
  methods: {

    search() {
      this.query.currentPage = 1;
      this.getShop();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getShop();
    },
    //获取用户列表
    getShop() {
      this.$http.post("/shop", this.query)
          .then(result => {
            result = result.data;
            if (result.success) {
              this.pageInfo = result.data;
            } else {
              this.$message({type: 'error', message: '查询失败'})
            }
          })
          .catch(result => {
            this.$message({type: 'error', message: '服务器异常'})
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        let id = row.id;
        this.$http.delete("/shop/"+id)
        .then(result=>{
         result= result.data;
         if (result.success){
           this.$message({type: 'success', message: '删除成功'})
           this.query.currentPage=1;
           this.getShop();
         }else {
           this.$message({type: 'error', message: '删除失败'})
         }
        })
      }).catch(() => {
        this.$message({type: 'error', message: '服务端异常'})
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.saveFormVisible=true;
      this.addForm=row
      //特殊处理department
      if (!this.addForm.department) {
        this.addForm.department = {
          id: null,
          name: "",
        }
      }else {
        this.$http.get("/department/"+row.department.id)
        .then(result=>{
            result=result.data;
            if (result.success){
              this.path=result.data.path;
              console.log(this.path)
              let param= this.path.split("/");  //param 打印出来是 Array(3) [ "", "1", "3" ]
              let temp=[];
              //回显部门
              for (let i=1; i<param.length;i++){
                //自己的id是number类型的，而数组中是string类型，所以需要处理一下才能回显
                temp.push(parseInt(param[i]));
              }
              console.log(temp)
              this.addForm.department=temp;
            }else {
              this.$message({message: '后端错误', type: 'error'});
            }
        })
        .catch(()=>{
          this.$message({message: '系统超时', type: 'error'});
        })

      }
      this.getDept();
    },
    //显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.addForm = {
        username: '',
        password: '',
        age: 0,
        email: "",
        headImage: "",
        department: {
          id: null,
          name: ""
        }
      };
      this.getDept();

    },
    //查询有哪些部门，方便下拉框回显等操作
    getDept(){
      this.$http.get("/department/tree")
      .then(result=>{
        result=result.data;
        if (result.success){
          this.deptTree=result.data;
        }else {
          this.$message({type: 'error', message: '查询失败'})
        }

      })
      .catch(result=>{
        this.$message({type: 'error', message: '服务端异常'})
      })
    },
    //新增/保存
    saveSubmit: function () {
      // console.log(this.addForm.department)
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {})
              .then(() => {
                let param=this.addForm;
                //拿到之前的parent数组  这里只需要显示他自己的父部门就行了，不需要父的父
                let array=param.department;
                //所以只需要拿数组的最后一个就行了
                param.department={id:array[array.length-1]}
                //最后将param作为参数传给后端，不能改动addForm  如果改了addForm会出现bug
                this.$http.put("/shop",param)
                .then(reuslt=>{
                  reuslt =reuslt.data;
                  if (reuslt.success){
                    this.$message({type: 'success', message: '保存成功'})
                    this.saveFormVisible=false;
                    this.query.currentPage=1;
                    this.getShop();
                  }else {
                    this.$message({type: 'error', message: '保存失败'})
                  }
                })
          }).catch(()=>{
            this.$message({type: 'info', message: '已取消'})
          })
        }
      });
    },
    selsChange: function (sels) {
      this.sels=sels;
    },
    //批量删除
    batchRemove: function () {
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
      let ids =  this.sels.map(item=>item.id);
       this.$http.patch("/shop",ids)
        .then(result=>{
          result= result.data;
          if (result.success){
            this.$message({type: 'success', message: '删除成功'})
            this.query.currentPage=1;
            this.getShop();
          }
        }).catch(result=>{
         this.$message({type: 'error', message: '后端原因删除失败了'})
       })

      }).catch(() => {
        this.$message({type: 'error', message: '服务器异常'})
      });
    }
  },
  mounted() {
    this.getShop();
  }
}

</script>

<style scoped>

</style>